package com.meterhuang.thread.zeroevenodd;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

/**
 * 1116. 打印零与奇偶数
 * http://leetcode-cn.com/problems/print-zero-even-odd/
 *
 * @author meterhuang
 * @date 2021/09/09 11:53
 */
public class ZeroEvenOddSemaphore {

	private int n;

	public ZeroEvenOddSemaphore(int n) {
		this.n = n;
	}

	private Semaphore zero = new Semaphore(1);

	private Semaphore odd = new Semaphore(0);

	private Semaphore even = new Semaphore(0);

	public void zero(IntConsumer printNumber) throws InterruptedException {
		for (int i = 1; i <= n; ++i) {
			zero.acquire();
			printNumber.accept(0);
			if (i % 2 == 1) {
				odd.release();
			} else {
				even.release();
			}
		}
	}

	public void even(IntConsumer printNumber) throws InterruptedException {
		for (int i = 2; i <= n;i = i + 2) {
			even.acquire();
			if (i % 2 == 0) {
				printNumber.accept(i);
			}
			zero.release();
		}
	}

	public void odd(IntConsumer printNumber) throws InterruptedException {
		for (int i = 1; i <= n;i = i + 2) {
			odd.acquire();
			if (i % 2 == 1) {
				printNumber.accept(i);
			}
			zero.release();
		}
	}
}
